package com.aisafer.fms.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aisafer.fms.client.dto.DownResp;
import com.aisafer.fms.config.AttachConfig;
import com.aisafer.fms.domain.AttachmentE;
import com.aisafer.fms.domain.OssMsg;
import com.aisafer.fms.enums.AttachmentEnums;
import com.aisafer.fms.mapper.AttachmentMapper;
import com.aisafer.fms.storage.StorageFactory;
import com.aisafer.fms.utils.AttachmentUtils;
import com.polaris.base.utils.string.JsonUtil;

/**
 * 文件上传到各个存储服务器
 * @author stevin
 */

@Service
public class AttachmentRoute {

	private static final Logger logger = LoggerFactory.getLogger(AttachmentRoute.class);
	
	@Autowired
	AttachmentMapper attachmentMapper;

	@Autowired
	AttachConfig attachConfig;

	@Autowired
	AttachmentService service;
	
	@Transactional
	public void broadcast(List<OssMsg>  ossList) {
		for(OssMsg oss : ossList) {
			if(AttachmentEnums.UPLOAD.name().equals(oss.getType())) {
				uploadFile(oss.getAttachid());
			}else if(AttachmentEnums.CLEAN.name().equals(oss.getType())) {
				service.cleanGroupFile(oss.getBatchid());
			}else {
				logger.error("不能处理的数据{}",JsonUtil.bean2Json(oss));
			}
		}
	}
	
	private void uploadFile(Long attachid) {
		DownResp down = service.getAttachStream(attachid);
		if(down == null || down.getContent() == null ||  down.getContent().length <=0) {
			logger.error("attach [{}] is empty.",attachid);
			return;
		}
		
		for (String storageType : AttachmentUtils.split(attachConfig.getSlave(), ",")) {
			AttachmentE attachmentE = new AttachmentE();
			attachmentE.setAttachid(attachid);
			attachmentE.setStorageKey(down.getFileName());
			StorageFactory.getInstance(storageType).upload(attachmentE, down.getContent());
		}
	}

}
